package com.ktjiaoyu.ktmall.servlet.admin;

import com.alibaba.fastjson.JSON;
import com.ktjiaoyu.ktmall.dao.CategoryDao;
import com.ktjiaoyu.ktmall.dao.impl.CategoryDaoImpl;
import com.ktjiaoyu.ktmall.entity.Category;
import com.ktjiaoyu.ktmall.service.CategoryService;
import com.ktjiaoyu.ktmall.service.impl.CategoryServiceImpl;
import com.ktjiaoyu.ktmall.utils.R;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Handler;

@WebServlet(name="CategoryServlet",urlPatterns = "/api/category/*")
public class CategoryServlet extends HttpServlet {
    private final CategoryService categoryService  = new CategoryServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");
        String path = req.getPathInfo();
        R result;
        if("/tree".equals(path)){
            List<Category> tree = categoryService.findTree();
            result = R.ok(tree);
        }else{
            List<Category> list = categoryService.findAll();
            result = R.ok(list);
        }
        PrintWriter out = resp.getWriter();
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
